<template>
  <div
    :ref="refName"
    :optionData="optionData"
    :title="title"
    style="width: 100%; height: 100%"
  />
</template>

<script>
import * as echarts from 'echarts'
export default {
  props: {
    refName: {
      type: String,
      default: 'ref'
    },
    optionData: {
      type: Object
    },
    title: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      chartData: null,
      namelist: [],
      serieslist: []
    }
  },
  watch: {
    optionData(newVal) {
      this.chartData = newVal
      this.changedata()
      this.init()
    }
  },
  mounted() {

  },
  methods: {
    changedata() {
      this.namelist = this.optionData.nameAndListValueDtos.map(res => {
        return res.name
      })

      this.serieslist = this.optionData.nameAndListValueDtos.map(res => {
        const commonProps = {
          name: res.name,
          type: res.type,
          emphasis: {
            focus: 'series'
          },
          data: res.values
        }
        return res.yAxisIndex ? {
          ...commonProps,
          data: res.values

        } : {
          ...commonProps,
          stack: res.stack,
          data: res.values,
          barWidth: 20
        }
      })
    },
    init() {
      const myChart = echarts.init(this.$refs[this.refName])
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        legend: {
          right: '5%',
          top: '2%',
          data: this.namelist
        },
        grid: {
          top: '20%',
          bottom: '5%',
          left: '0%',
          right: '0%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: this.chartData != null ? this.optionData.dateStrs : [],
            axisPointer: {
              type: 'shadow'
            },
            axisTick: {
              show: false
            }
          }
        ],
        yAxis: this.optionData.yAxis || [],
        series: this.serieslist
      }

      if (option) {
        myChart.setOption(option)
      }
    }
  }
}
</script>
